﻿//JumbotCms_4.1 Final
using System;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using Jumbot.Common;
using JumbotCms.Common;
namespace JumbotCms.WebFile.Admin
{
    public partial class _extendajax : JumbotCms.API.AdminCenter
    {
        private string _operType = string.Empty;
        private string _response = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CheckFormUrl())
            {
                Response.Write("提交有误");
                Response.End();
            }
            Admin_Load("0000", "json");
            this._operType = q("oper");
            switch (this._operType)
            {
                case "ajaxGetList":
                    ajaxGetList();
                    break;
                case "install":
                    ajaxInstall();
                    break;
                case "ajaxBatchOper":
                    ajaxBatchOper();
                    break;
                case "move":
                    ajaxMove();
                    break;
                case "ajaxDel":
                    ajaxDel();
                    break;
                case "new":
                    ajaxNew();
                    break;
                case "ajaxCreatePluginFile":
                    ajaxCreatePluginFile();
                    break;
                default:
                    DefaultResponse();
                    break;
            }
            Response.Write(this._response);
        }

        private void DefaultResponse()
        {
            this._response = JsonResult(0, "未知操作");
        }
        private void ajaxGetList()
        {
            doh.Reset();
            if (q("enabled") != "1")
                doh.SqlCmd = "Select [Id],[Title],[Name],[Author],[Info],[Type],[pId],[BaseTable],[ManageUrl],[Locked],[Enabled] FROM [jcms_normal_extends] ORDER BY pid";
            else
                doh.SqlCmd = "Select [Id],[Title],[Name],[Author],[Info],[Type],[pId],[BaseTable],[ManageUrl],[Locked],[Enabled] FROM [jcms_normal_extends] WHERE [Enabled]=1 ORDER BY pid";
            DataTable dt = doh.GetDataTable();
            this._response = "{result :\"1\",returnval :\"操作成功\"," + Jumbot.Common.JsonHelp.DtToSON(dt) + "}";
        }
        private void ajaxMove()
        {
            string id = f("id");
            string isUp = f("up");
            if (id == "0")
            {
                this._response = JsonResult(0, "ID错误");
                return;
            }
            doh.Reset();
            doh.ConditionExpress = "id=@id";
            doh.AddConditionParameter("@id", id);
            string pId = doh.GetValue("jcms_normal_extends", "pId").ToString();

            string temp;
            doh.Reset();
            if (isUp == "1")
            {
                doh.ConditionExpress = "pId<@pId ORDER BY pId desc";
                doh.AddConditionParameter("@pId", pId);
            }
            else
            {
                doh.ConditionExpress = "pId>@pId ORDER BY pId";
                doh.AddConditionParameter("@pId", pId);
            }
            temp = doh.GetValue("jcms_normal_extends", "pId").ToString();
            if (temp != "")
            {
                doh.Reset();
                doh.ConditionExpress = "pId=@pId";
                doh.AddConditionParameter("@pId", temp);
                doh.AddFieldItem("pId", "-100000");
                doh.Update("jcms_normal_extends");
                doh.Reset();
                doh.ConditionExpress = "id=@id";
                doh.AddConditionParameter("@id", id);
                doh.AddFieldItem("pId", temp);
                doh.Update("jcms_normal_extends");
                doh.Reset();
                doh.ConditionExpress = "pId=@pId";
                doh.AddConditionParameter("@pId", "-100000");
                doh.AddFieldItem("pId", pId);
                doh.Update("jcms_normal_extends");
                createPluginFile();
                this._response = JsonResult(1, "成功移动");
            }
            else
                this._response = JsonResult(0, "无须移动");
        }
        private void ajaxDel()
        {
            string eId = f("id");
            if (eId != "")
            {
                doh.Reset();
                doh.ConditionExpress = "id=@id";
                doh.AddConditionParameter("@id", eId);
                object[] _values = doh.GetValues("jcms_normal_extends", "Name,Locked,Enabled,BaseTable");
                string eName = _values[0].ToString();
                string eLocked = _values[1].ToString();
                string eEnabled = _values[2].ToString();
                string _delTables = _values[3].ToString();
                if (eLocked == "1")
                {
                    this._response = JsonResult(0, "锁定的插件不可删");
                    return;
                }

                if (eEnabled == "1")
                {
                    this._response = JsonResult(0, "先把插件禁用再卸载");
                    return;
                }

                if (_delTables.Trim().Length > 0)//需要删除插件表
                {
                    string[] _delTable = _delTables.Split(',');
                    for (int i = 0; i < _delTable.Length; i++)
                    {
                        doh.Reset();
                        doh.DropTable(_delTable[i]);
                    }
                }
                //删除插件整个目录
                Jumbot.Common.DirFile.DeleteDir(site.Dir + "extends/" + eName + "/");
                doh.Reset();
                doh.ConditionExpress = "id=@id";
                doh.AddConditionParameter("@id", eId);
                doh.Delete("jcms_normal_extends");
                createPluginFile();
                this._response = JsonResult(1, "插件成功删除");
            }
            else
                this._response = JsonResult(0, "参数错误");
        }
        /// <summary>
        /// 执行批量操作
        /// </summary>
        /// <param name="oper"></param>
        /// <param name="ids"></param>
        private void ajaxBatchOper()
        {
            string act = q("act");
            string ids = f("ids");
            string[] idValue;
            idValue = ids.Split(',');
            string ClassId = string.Empty;
            if (act == "pass")
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    doh.AddFieldItem("Enabled", 1);
                    doh.Update("jcms_normal_extends");
                }
                createPluginFile();
            }
            else if (act == "nopass")
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    doh.AddFieldItem("Enabled", 0);
                    doh.Update("jcms_normal_extends");
                    //删除前台插件文件
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    string _eName = doh.GetValue("jcms_normal_extends", "Name").ToString();
                    Jumbot.Common.DirFile.DeleteFile("~/_data/html/p_" + _eName + ".htm");
                    Jumbot.Common.DirFile.DeleteFile("~/_data/json/p_" + _eName + ".js");
                    Jumbot.Common.DirFile.DeleteFile("~/_data/style/p_" + _eName + ".js");
                }
                createPluginFile();
            }
            this._response = JsonResult(1, "操作成功");
        }
        private void ajaxNew()
        {
            DirectoryInfo di = new DirectoryInfo(Server.MapPath(site.Dir + "extends/"));
            DirectoryInfo[] directorylist = di.GetDirectories();
            string tempstr = "table:[";
            int extendcount = 0;
            string _title = "";
            string _name = "";
            string _author = "";
            string _type = "";
            foreach (DirectoryInfo dii in directorylist)
            {
                if (!Jumbot.Common.DirFile.FileExists(site.Dir + "extends/" + dii.Name + "/install.config"))
                    continue;
                _title = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + dii.Name + "/install", "Title");
                _name = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + dii.Name + "/install", "Name");
                _author = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + dii.Name + "/install", "Author");
                _type = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + dii.Name + "/install", "Type");

                doh.Reset();
                doh.ConditionExpress = "name=@name";
                doh.AddConditionParameter("@name", _name);
                if (doh.Exist("jcms_normal_extends"))
                    continue;
                tempstr += ",{title: '" + _title + "'," +
                    "name: '" + _name + "'," +
                    "author: '" + _author + "'," +
                    "type: '" + _type + "'}";
                extendcount++;
            }
            tempstr += "]";
            tempstr = tempstr.Replace("table:[,", "table:[");
            this._response = "{result :\"1\",returnval :\"操作成功\",recordcount:" + extendcount + "," + tempstr + "}";
        }
        private void ajaxInstall()
        {
            string _name = f("name");
            if (!Jumbot.Common.DirFile.FileExists(site.Dir + "extends/" + _name + "/install.config"))
            {
                this._response = JsonResult(0, "插件的安装文件损坏或不存在");
                return;
            }
            doh.Reset();
            doh.ConditionExpress = "id>0 ORDER BY pId desc";
            int pId = Jumbot.Common.Validator.StrToInt(doh.GetValue("jcms_normal_extends", "pId").ToString(), 0);
            string _Title = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "Title");
            string _Author = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "Author");
            string _Info = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "Info");
            string _Type = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "Type");
            string _BaseTable = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "BaseTable");
            string _ManageUrl = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "ManageUrl");
            int _Locked = Jumbot.Common.Validator.StrToInt(Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "Locked"), 0);
            if (_BaseTable != "")//需要安装数据库
            {
                string _SqlScriptText = Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "extends/" + _name + "/install", "SqlScript" + base.DBType);
                string _SqlScriptFile = site.Dir + "extends/" + _name + "/install.sql";
                Jumbot.Common.DirFile.SaveFile(_SqlScriptText, _SqlScriptFile);
                if (!ExecuteSqlInFile(Server.MapPath(_SqlScriptFile)))
                {
                    this._response = JsonResult(0, "数据表创建有误,可能已存在");
                    return;
                }
            }
            doh.Reset();
            doh.AddFieldItem("Title", _Title);
            doh.AddFieldItem("Name", _name);
            doh.AddFieldItem("Author", _Author);
            doh.AddFieldItem("Info", _Info);
            doh.AddFieldItem("Type", _Type);
            doh.AddFieldItem("BaseTable", _BaseTable);
            doh.AddFieldItem("ManageUrl", _ManageUrl);
            doh.AddFieldItem("Locked", _Locked);
            doh.AddFieldItem("Enabled", 0);
            doh.AddFieldItem("pId", pId + 1);
            doh.Insert("jcms_normal_extends");
            this._response = JsonResult(1, "插件安装成功");
        }
        private void ajaxCreatePluginFile()
        {
            createPluginFile();
            this._response = JsonResult(1, "插件文件更新完成");
        }
        private void createPluginFile()
        {
            doh.Reset();
            doh.SqlCmd = "Select [Id],[Title],[Name] FROM [jcms_normal_extends] WHERE [Enabled]=1 ORDER BY pid";
            DataTable dt = doh.GetDataTable();

            string tempfile = "";
            StringBuilder sb_commonjs = new StringBuilder("");
            StringBuilder sb_stylecss = new StringBuilder("");
            string TempStr;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb_commonjs.Append("\r\n\r\n/*--引入插件" + dt.Rows[i]["Title"].ToString() + "js--*/\r\n");
                sb_commonjs.Append("\r\nvar Plugin" + dt.Rows[i]["Name"].ToString() + "\t= true;\r\n");
                if (File.Exists(Server.MapPath(site.Dir) + "extends\\" + dt.Rows[i]["Name"].ToString().ToLower() + "\\include\\common.js"))
                {
                    TempStr = File.ReadAllText(Server.MapPath(site.Dir) + "extends\\" + dt.Rows[i]["Name"].ToString().ToLower() + "\\include\\common.js");
                    sb_commonjs.Append(TempStr);
                }
                if (File.Exists(Server.MapPath(site.Dir) + "extends\\" + dt.Rows[i]["Name"].ToString().ToLower() + "\\include\\common.css"))
                {
                    TempStr = File.ReadAllText(Server.MapPath(site.Dir) + "extends\\" + dt.Rows[i]["Name"].ToString().ToLower() + "\\include\\common.css");
                    sb_stylecss.Append("\r\n\r\n/*--引入插件" + dt.Rows[i]["Title"].ToString() + "css--*/\r\n" + TempStr);
                }
            }
            dt.Clear();
            dt.Dispose();

            tempfile = Server.MapPath(site.Dir) + "_data\\style\\extends.js";
            SaveJsFile(sb_commonjs.ToString(), tempfile);

            string _tempcsstext = string.Empty;
            JumbotCms.API.PageCSSManage pcm = new JumbotCms.API.PageCSSManage();
            doh.Reset();
            doh.SqlCmd = "SELECT [ID],[Title],[Source],[BodyWidth],[LeftWidth],[RightWidth],[TitleColor],[BorderColor],[TintBackground],[DarkBackground] FROM [jcms_normal_skins] ORDER BY Id asc";
            DataTable dtSkins = doh.GetDataTable();
            for (int j = 0; j < dtSkins.Rows.Count; j++)
            {
                _tempcsstext = sb_stylecss.ToString();
                _tempcsstext = _tempcsstext.Replace("{site.Dir}", site.Dir);//替换跟目录路径
                pcm.Path = dtSkins.Rows[j]["Source"].ToString();
                pcm.BodyWidth = Str2Int(dtSkins.Rows[j]["BodyWidth"].ToString());
                pcm.LeftWidth = Str2Int(dtSkins.Rows[j]["LeftWidth"].ToString());
                pcm.RightWidth = Str2Int(dtSkins.Rows[j]["RightWidth"].ToString());
                pcm.TitleColor = dtSkins.Rows[j]["TitleColor"].ToString();
                pcm.BorderColor = dtSkins.Rows[j]["BorderColor"].ToString();
                pcm.TintBackground = dtSkins.Rows[j]["TintBackground"].ToString();
                pcm.DarkBackground = dtSkins.Rows[j]["DarkBackground"].ToString();
                pcm.Oper(ref _tempcsstext);
                tempfile = Server.MapPath(site.Dir) + "skins\\" + pcm.Path + "\\css\\extends.css";
                SaveCssFile(_tempcsstext, tempfile);
            }
            dtSkins.Clear();
            dtSkins.Dispose();
        }
    }
}